import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { Sentence } from 'src/app/model/sentence';
import { SwiperComponent } from 'swiper/angular';
import { ReadingService } from '../../services/reading.service';
// import Swiper core and required modules
import SwiperCore, { Virtual } from 'swiper';

// install Swiper modules
SwiperCore.use([Virtual]);

@Component({
  selector: 'app-slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.scss'],
})
export class SliderComponent implements OnInit, OnChanges {
  @ViewChild('swiper', { static: true })
  public slides: SwiperComponent;

  @Input()
  public englishChecked: boolean;
  @Input()
  public chineseChecked: boolean;
  @Input()
  public sentences: Sentence[];
  @Input()
  public currentSentence: Sentence;

  @Output()
  public slideNext = new EventEmitter();
  @Output()
  public slidePrevious = new EventEmitter();

  constructor(private readingService: ReadingService) {}
  public ngOnChanges(changes: SimpleChanges): void {
    if (changes.sentences && changes.sentences.currentValue !== changes.sentences.previousValue) {
      if (this.slides?.swiperRef) {
        this.slides.swiperRef.activeIndex = 0;
      }
    }
    if (changes.currentSentence && changes.currentSentence.currentValue !== changes.currentSentence.previousValue) {
      const s = changes.currentSentence.currentValue;
      const index = this.sentences.findIndex((n) => n.id === s.id);
      if (this.readingService.triggerSource === 'player') {
        setTimeout(() => {
          this.slides?.swiperRef?.slideTo(index + 1, 400, false);
        }, 100);
      }
    }
  }

  public ngOnInit() {
    this.readingService.isPlayingSubject.subscribe((lock) => {
      if (lock == null) {
        return;
      }
      this.slides.swiperRef.allowTouchMove = !lock;
    });
  }

  public sliderMove(event: any) {
    this.readingService.setTriggerSource('slider');
  }

  public slideNextTransitionEnd(event: any) {
    if (!this.slides?.swiperRef) {
      return;
    }
    const index = this.slides?.swiperRef?.realIndex;
    this.slideNext.emit(index + 1);
  }
  public slidePrevTransitionEnd(event: any) {
    if (!this.slides?.swiperRef) {
      return;
    }
    const index = this.slides?.swiperRef?.realIndex;
    this.slidePrevious.emit(index + 1);
  }
}
